import Toast from 'tdesign-miniprogram/toast/index';
import request from '../../utils/request';

Page({
  externalClasses: ['theme-wrapper-class'],
  data: {
    id: 0,
    originFiles: [
    ],
    successNum: 0,
    evaDesc: '',
    evaImages: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
  },
  privateData: {
    verifyTips: '',
  },
  onLoad(options) {
    const { id } = options;
    var currentCar = getApp().globalData.currentCar;
    if (currentCar != null) {
      if (currentCar.id == id) {
        var files = []
        var evaImgs = [];
        if (currentCar.evaImages != null && currentCar.evaImages.length > 0) {
          evaImgs = currentCar.evaImages.split(',');
        }
        if (evaImgs != null) {
          for (var i = 0; i < evaImgs.length; i++) {
            files.push({ url: getApp().globalData.imageUrl + evaImgs[i] })
          }
        }
        this.setData({ evaDesc: currentCar.evaDesc, originFiles: files })

      } else {
        getApp().globalData.currentCar = null;
      }
    }
    this.setData({ id: id });
  },

  handleSuccess(e) {
    const { files } = e.detail;
    console.log("success", files)
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },

  hasSava: false,

  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    const { value = '' } = e.detail;
    this.setData(
      {
        [`${item}`]: value,
      },
      () => {
        const { isLegal, tips } = this.onVerifyInputLegal();
        this.setData({
          submitActive: isLegal,
        });
        this.privateData.verifyTips = tips;
      },
    );
  },

  onVerifyInputLegal() {
    const { evaDesc, originFiles } = this.data;

    if (!evaDesc || !evaDesc.trim()) {
      return {
        isLegal: false,
        tips: '请输入评估详情',
      };
    }
    if (!originFiles || originFiles.length == 0) {
      return {
        isLegal: false,
        tips: '请上传评估图片',
      };
    }
    return {
      isLegal: true,
      tips: '添加成功',
    };
  },

  formSubmit() {
    var that = this;
    this.setData({ evaImages: [] })
    const { submitActive, originFiles } = this.data;
    const { isLegal, tips } = this.onVerifyInputLegal();
    if (!isLegal) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: tips,
        icon: '',
        duration: 1000,
      });
      return;
    }
    //upload image
    if (originFiles.length > 0) {
      originFiles.forEach(file => this.uploadFile(file))
    } else {
      this.saveEva();
    }
  },
  uploadFile(file) {
    var that = this;
    if (file.url.indexOf(getApp().globalData.imageUrl) != -1) {
      var evaImages = that.data.evaImages;
      evaImages.push(file.url.replace(getApp().globalData.imageUrl, ''));
      that.setData({ evaImages: evaImages })
      if (evaImages.length == that.data.originFiles.length) {
        that.saveEva();
      }
    } else {
      wx.compressImage({
        src: file.url,
        quality: 70,
        //   compressedWidth:400,
        success(res) {
          console.log("压缩成功，上传", res.tempFilePath)
          that.uploadServer(res.tempFilePath)
        },
        fail() {
          console.log("压缩失败，上传", file.url)
          that.uploadServer(file.url)
        }
      })
    }
  },
  uploadServer(tempPhotoUrl) {
    var that = this;
    wx.showToast({ icon: "loading", title: "正在上传……" });
    that.setData({ uploading: true })
    request.upload('/car/user/uploadFile', tempPhotoUrl, function (res) {
      that.setData({ uploading: false })
      if (res.code == 0) {
        var evaImages = that.data.evaImages;
        evaImages.push(res.data);
        that.setData({ evaImages: evaImages })
        if (evaImages.length == that.data.originFiles.length) {
          that.saveEva();
        }
      } else {
        // wx.showModal({ title: '提示', content: '图片上传', showCancel: false });
        console.log("图片上传失败", res.message);
      }
    })
  },
  saveEva() {
    var that = this;
    var evaImages = '';
    for (var i = 0; i < this.data.evaImages.length; i++) {
      if (evaImages.length > 0) evaImages = evaImages + ",";
      evaImages = evaImages + this.data.evaImages[i];
    }
    var url = "/car/user/stock/evaluate"
    var data = {
      id: this.data.id,
      evaDesc: this.data.evaDesc,
      evaImages: evaImages
    }
    request.post(url, data, function (res) {
      if (res.code == 0) {
        that.hasSava = true;
        var pages = getCurrentPages();
        if (pages.length > 1) {
          var prePage = pages[pages.length - 2];
          // 调用上个页面的方法 
          prePage.triggerChangeData()
        }

        wx.navigateBack({ delta: 1 });
      } else {
        wx.showModal({ title: '提示', content: res.message, showCancel: false });
      }
    })
  }

});
